package com.likianta.anykey;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
 * Created by Likianta_Dodoora on 2017/12/8 0008.
 */

public class GroupAdapter extends RecyclerView.Adapter<GroupAdapter.GroupViewHolder> {
    
    private List<Group> groups;
    private Context context;
    private String name;
    private MyItemClickListener listener;
    
    public GroupAdapter(List<Group> groups) {
        this.groups = groups;
    }
    
    @Override
    public GroupViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        
        View view = LayoutInflater.from(context).inflate(R.layout.group_type2, parent, false);
        return new GroupViewHolder(view, listener);
    }
    
    @Override
    public void onBindViewHolder(GroupViewHolder holder, int position) {
        Group group = groups.get(position);
        name = group.getGroupName();
        holder.groupIcon.setBackgroundResource(group.getIconId());
        holder.groupName.setText(name);
    }
    
    public String getGroupName() {
        return name;
    }
    
    
    @Override
    public int getItemCount() {
        return groups.size();
    }
    
    public void add(int position, Group group) {
        groups.add(position, group);
        notifyItemInserted(position);
    }
    
    public void remove(Context context, int position) {
        if (position < 0) {
            Toast.makeText(context, "列表中并没有结果!", Toast.LENGTH_SHORT).show();
        } else {
            groups.remove(position);
            notifyItemRemoved(position);
        }
    }
    
    public void setItemClickListener(MyItemClickListener listener) {
        this.listener = listener;
    }
    
    /**
     * 创建一个回调接口，用来监听holder的点击事件
     */
    public interface MyItemClickListener {
        void onItemClick(View view, int position);
    }
    
    static class GroupViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView groupIcon;
        TextView groupName;
        private MyItemClickListener listener;
        
        public GroupViewHolder(View view, MyItemClickListener listener) {
            super(view);
            groupIcon = (ImageView) view.findViewById(R.id.group_icon);
            groupName = (TextView) view.findViewById(R.id.group_name);
            this.listener = listener;
            view.setOnClickListener(this);
        }
        
        @Override
        public void onClick(View view) {
            if (listener != null) {
                listener.onItemClick(view, getLayoutPosition());
            }
        }
    }
}
